<script setup>
import { SendPostRequest } from './lib'
import { ref } from 'vue'

let props = defineProps(['title', 'id'])

let is_editing = ref(false)
let newContent = ref('')

function onKeyUp(event) {
  newContent.value = event.target.value
}

function saveTodo() {
  const apiUrl = 'http://127.0.0.1:1900/api/v1/todo/update'

  SendPostRequest(
    apiUrl,
    {
      id: props.id,
      title: newContent.value,
    },
    () => {
      is_editing.value = false
    },
  )
}

function toggleEdit() {
  is_editing.value = !is_editing.value
}

function cancelEditing() {
  is_editing.value = false
}

function deleteTodo(id) {
  SendDeleteRequest(id, () => {
    alert('删除成功')
  })
}

function SendDeleteRequest(id, callback) {
  const apiUrl = 'http://127.0.0.1:1900/api/v1/todo/delete'

  SendPostRequest(
    apiUrl,
    {
      id: id,
    },
    callback,
  )
}
</script>

<template>
  <li>
    <div v-if="is_editing">
      <input type="text" :value="title" @keyup="onKeyUp" />
      <button @click="saveTodo">保存</button>
      <button @click="cancelEditing">X</button>
    </div>
    <div v-else>
      <input type="checkbox" />
      <span class="title">{{ title }}</span>
      <button @click="deleteTodo(id)">X</button>
      <button @click="toggleEdit">Edit</button>
    </div>
  </li>
</template>

<style scoped>
.title {
  font-weight: bold;
}
</style>
